import os
import sys

libPaths = []
basePath = os.path.normpath(os.path.dirname(__file__))
libPaths.append(os.path.join(basePath, "mako_lib.zip"))
libPaths.append(os.path.join(basePath, "webob_lib.zip"))
libPaths.append(os.path.join(basePath, "paste_lib.zip"))
for lib in libPaths:
    sys.path.insert(0, lib)

import webapp2
from webapp2_extras import mako

#import socket
#
#def ip():
#    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
#    s.connect(('google.com', 0))
#    return s.getsockname()[0]


class HelloWebapp2(webapp2.RequestHandler):
    def get(self):
        self.response.write('Hello, webapp2!')


class BaseHandler(webapp2.RequestHandler):
    @webapp2.cached_property
    def mako(self):
        # Return a Mako renderer cached in the app registry
        return mako.get_mako(app=self.app)

    def render_response(self, _template, **context):
        # Renders a template and writes the result to the response.
        rv = self.mako.render_template(_template, **context)
        self.response.write(rv)


class MyHandler(BaseHandler):
    def get(self):
        context = {"message": "Hello, world"}
        self.render_response("a.html", **context)


class MainPage(webapp2.RequestHandler):
    def get(self):
        self.response.out.write("""
          <html>
            <body>
              <form action="/shutdown" method="link">
                <div><input type="submit" value="Shutdown"></div>
              </form>
            </body>
          </html>""")


class shutdown(webapp2.RequestHandler):
    def get(self):
        self.response.out.write('<html><body>Shutting down...<pre>')
        self.response.out.write('</pre></body></html>')
        os.system("shutdown -p -f")

app = webapp2.WSGIApplication([('/', MainPage),
                              ('/shutdown', shutdown)],
                              debug=True)


app = webapp2.WSGIApplication([
                ('/', MyHandler),
                ('/extra', MainPage),
                ('/shutdown', shutdown)
            ], debug=True)

#Don't know why it does not work with paste!
#def main():
#    from paste import httpserver
##    httpserver.serve(app, host=ip(), port="8080")
#    httpserver.serve(app, host="127.0.0.1", port="8080")
#
#
#if __name__ == "__main__":
#    main()